package network.udp.demo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @program: baseModule
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-26 15:33
 **/
public class UdpReceive {
    public static void main(String[] args) {
        receive();
    }

    private static void receive() {
        // UDP接收数据：因为接收端不知道发送端什么时候停止发送，故采用死循环接收
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(9000);
            while (true) {
                byte[] bytes = new byte[1024];
                DatagramPacket p = new DatagramPacket(bytes, bytes.length);
                socket.receive(p);
                String s = new String(p.getData(), 0, p.getLength());

                System.out.println(s);
                if (s.equals("886")) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

}
